﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Gargoyle.ZZT
{
    public class ThingCollection
    {
        private int capacity;
        private int count = 0;
        private Thing[] things;

        public ThingCollection(int newCapacity)
        {
            capacity = newCapacity;
            things = new Thing[capacity + 1];
            for (int i = 0; i <= capacity; i++)
                things[i] = new Thing();
        }

        public Thing this[int index]
        {
            get
            {
                return things[index];
            }
            set
            {
                things[index] = value;
            }
        }

        public void Add(Thing item)
        {
            if (count < capacity)
            {
                things[count] = item;
                count++;
            }
        }

        public int Capacity
        {
            get
            {
                return capacity;
            }
        }

        public int Count
        {
            get
            {
                return count;
            }
        }

        public int IndexOf(Thing item)
        {
            for (int i = 0; i < count; i++)
            {
                if (things[i].Equals(item))
                    return i;
            }
            return -1;
        }

        public void Remove(Thing item)
        {
            int index = IndexOf(item);

            if (index >= 0)
            {
                RemoveAt(index);
            }
        }

        public void RemoveAt(int index)
        {
            if (index < count)
            {
                for (int i = 0; i < count; i++)
                {
                    Thing thing = things[i];

                    if (thing.Follower == index)
                        thing.Follower = -1;
                    else if (thing.Follower > index)
                        thing.Follower--;

                    if (thing.Leader == index)
                        thing.Leader = -1;
                    else if (thing.Leader > index)
                        thing.Leader--;
                }

                for (int i = index; i < count; i++)
                {
                    things[i].CopyFrom(things[i + 1]);
                }

                count--;
            }
        }
    }
}
